package com.zpf.filter;

//鉴权过滤器，判断tomcat的session 中是否有用户对象信息
//判断消费者是否登录

import com.zpf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class PermFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //1.获取用户的访问路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uriStr = request.getRequestURI();
        //2.判断用户路径，放行所有静态资源，放行用户登录路径，放行用户注册，首页，商品查询等路径
        //判断路径的扩展名，如果是js文件放行，业务js文件和jsp文件差一个字母，则，使用contains无法判断
        //字符串切割之前，判断大于0
        if(uriStr.lastIndexOf(".")>0) {
            String exStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (exStr != null) {
                if ("js".equals(exStr)) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        if(uriStr.contains("/login")||uriStr.contains("/code")
                ||uriStr.contains("/user")||uriStr.contains("/register")
                ||uriStr.contains("/admin")  ||uriStr.contains("/type")
                ||uriStr.contains("/goods")||uriStr.contains("/cart")
                ||uriStr.contains(".js")||uriStr.contains(".css")
                ||uriStr.contains(".jpg")||uriStr.contains(".png")
                ||uriStr.contains(".gif")||uriStr.contains(".eot")
                ||uriStr.contains(".svg")||uriStr.contains(".ttf")
                ||uriStr.contains(".woff")||uriStr.contains(".woff2")
              ){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3.获取会话session对象
        HttpSession session = request.getSession();
        //4.p判断会话中是否有用户的对象信息
        User user = (User) session.getAttribute("loginUser");

        if (user != null) {
            //5.非空判断，放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            response.sendRedirect("/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
